#include "client_us.h"
#include <string.h>
#include <stdlib.h>
// 判断 成功是0，失败是-1
int action_flag(int code) {
    if (code == SUCCESS) {
        return 0;
    } else {
        return -1;
    }
}



/*
 *初始化
 *参数: daunko:端口
 *      ip: IP地址
 *返回值：套接字
 * */
int regis_init(int duanko, char *ip)
{
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd<0){
        perror("socket");
        return -1;
    }

    //声明方向
    struct sockaddr_in server;
    server.sin_family=AF_INET;//地址族  代表选择IPv4
    server.sin_port=htons(duanko);//端口号 //因为有大小端序之分，所以要转换端序
    server.sin_addr.s_addr=inet_addr(ip);//IP地址 因为网络二进制

    //主动连接
    if (connect(sockfd, (struct sockaddr *)&server, sizeof(server))){
        perror("connect");
        return -1;
    }

    return sockfd;
}



/*
 *注册账号
 *参数: sockfd:套接字
 *      username:用户名
 *      passeord:密码
 *返回值：成功：0； 失败：-1；
 * */
int register_account(int sockfd, char *username, char *password)
{
	char buf[JSON_SIZE_MAX];
    user_t ss1;
    strcpy(ss1.user_name,username);
    strcpy(ss1.passwd,password);

    //将用户结构体转化为json字符串
    const char *us = user_to_json(ss1);

    //交互消息通用结构
    send_message(sockfd, message_init(USER_REGISTER,us,"注册"), buf);
	//strcpy(data,rep);
	//free(rep);

    return action_flag(json_get_int(buf,"action"));
}



/*
 *登录账号
 *参数: sockfd:套接字
 *      username:用户名
 *      passeord:密码
 *返回值：成功：0； 失败：-1；
 * */
int log_in(int sockfd, char *username, char *password)
{
	char buf[JSON_SIZE_MAX];
    user_t ss1;
    strcpy(ss1.user_name,username);
    strcpy(ss1.passwd,password);

    //将用户结构体转化为json字符串
    const char *us = user_to_json(ss1);

    //交互消息通用结构
    send_message(sockfd, message_init(USER_LOGIN, us,"登录"), buf);

    if (!action_flag(json_get_int(buf,"action"))){
        return atoi(json_get_string(buf, "text"));
    }

    return -1;
}


//搜索用户
int seek_us(int sockfd, char *username)
{
	char buf[JSON_SIZE_MAX];
    char *data = json_set_char(data,"user_name",username);

    //交互消息通用结构
    send_message(sockfd, message_init(USER_FIND_BY_NAME, data,"搜索用户"), buf);

    //成功返回好友ID
    if (!action_flag(json_get_int(buf,"action"))){
        return atoi(json_get_string(buf, "text"));
    }

    return -1;
    
}

//查看所有好友
int seeks_us(int sockfd, int user_id, user_t **frs)
{
	char buf[JSON_SIZE_MAX];
    char *data = json_set_int(data,"user_id",user_id);

    //交互消息通用结构
    send_message(sockfd, message_init(USER_FIND_F_ALL, data,"搜索用户"), buf);

    //成功返回
    if (!action_flag(json_get_int(buf,"action"))){
        char *p = json_get_string(buf, "data");
		//int len = atoi(json_get_string(buf, "text"));
		printf("p:%s\n",p);
		
		//将传过来的数据的接包成user_t的数组
		return user_group(p, frs);
    }

    return -1;
    
}


/*
 *添加好友
 *参数: sockfd:套接字
 *		user_id:用户ID
 *		fr_id:好友id
 *返回值：成功：0； 失败：-1；
 * */
int add_us(int sockfd, int user_id, int fr_id)
{
	
	char buf[JSON_SIZE_MAX];

	char *data = json_set_int(NULL,"user_id",user_id);
	data = json_set_int(data,"fr_id",fr_id);
	printf("%s\n",data);

	//交互消息通用结构
	send_message(sockfd, message_init(USER_ADD_F, data,"添加好友"), buf);

	return action_flag(json_get_int(buf,"action"));
}



/*
 *删除好友
 *参数: sockfd:套接字
 *      username:用户名
 *返回值：成功：0； 失败：-1；
 * */
int delete_us(int sockfd, int user_id,int fr_id)
{
	char buf[JSON_SIZE_MAX];
    char *data = json_set_int(NULL,"user_id",user_id);
    data = json_set_int(data,"fr_id",fr_id);
    send_message(sockfd, message_init(USER_DELETE_F,data,"删除好友"), buf);
    return action_flag(json_get_int(buf,"action"));
}


//用户私聊
int us_private(int sockfd, int user_id, int fr_id, char *username, char *content)
{		
	char buf[JSON_SIZE_MAX];
	char *data = json_set_int(NULL,"user_id",user_id);
	char *data1 = json_set_int(data,"fr_id",fr_id);
	char *data2 = json_set_char(data1,"user_name",username);
	char *data3 = json_set_char(data2,"content",content);
	printf("%s\n",data3);

	//交互消息通用结构
	send_message(sockfd, message_init(USER_SEND_MESSAGE_USER, data3,"私聊"), buf);

	return action_flag(json_get_int(buf,"action"));
}


//创造群组
int create_groups(int sockfd, int user_id, char *group_name, char *creator_name, char *remark)
{
	char buf[JSON_SIZE_MAX];
	char *data = json_set_int(NULL,"user_id",user_id);
	char *data1 = json_set_char(data,"group_name",group_name);
	char *data2 = json_set_char(data1,"creator_name",creator_name);
	char *data3 = json_set_char(data2,"remark",remark);
	printf("%s\n",data3);

	//交互消息通用结构
	send_message(sockfd, message_init(USER_CRT_GROUP , data3,"创建群组"), buf);

	return action_flag(json_get_int(buf,"action"));
}


//加入群组
int join_group(int sockfd, int group_id, int member_id)
{
	char buf[JSON_SIZE_MAX];
	char *data = json_set_int(NULL,"group_id",group_id);
	data = json_set_int(data,"member_id",member_id);
	printf("%s\n",data);

	//交互消息通用结构
	send_message(sockfd, message_init(USER_JOIN_GROUP, data,"加入群组"), buf);

	return action_flag(json_get_int(buf,"action"));
}


//用户群聊
int us_group_chat(int sockfd, int user_id, int group_id, char *username, char *content)
{		
	char buf[JSON_SIZE_MAX];
	char *data = json_set_int(NULL,"user_id",user_id);
	char *data1 = json_set_int(data,"group_id",group_id);
	char *data2 = json_set_char(data1,"user_name",username);
	char *data3 = json_set_char(data2,"content",content);
	printf("%s\n",data3);

	//交互消息通用结构
	send_message(sockfd, message_init(USER_SEND_MESSAGE_GROUP, data3,"群聊"), buf);

	return action_flag(json_get_int(buf,"action"));
}




/*
 *与服务器交互
 * */
void send_message(int sockfd,char *message, char *buf) {
    //交互消息通用结构
    const char *p = message;
    if (send(sockfd, p, JSON_SIZE_MAX,0) > 0) {
        printf("发送成功 \n");
    }

	bzero(buf,sizeof(buf));
    if (recv(sockfd,buf,JSON_SIZE_MAX,0) > 0 ) {
        printf("接到消息%s \n",buf);
    }
}


//将传过来的数据的接包成user_t的数组
int user_group(char *p, user_t **frs)
{
	//解包
	//1>将p转化为数组对象
	struct json_object*	obj_arrs=json_tokener_parse(p);

	//2>获取数组对象里面有多少个数据
	int len=json_object_array_length (obj_arrs);
	printf("len :%d\n",len);
	*frs = (user_t*)malloc(len * sizeof(user_t));	
	if (*frs == NULL) {
		// 内存分配失败
		exit(EXIT_FAILURE);
	}
	
	//3>循环解包
	int i;
	struct json_object *objects;//json大对象
	struct json_object *obj_ids;//json小对象 id 
	struct json_object *obj_names;//json小对象 name 
	//4>循环操作
	for(i=0;i<len;i++){
		//从数组对象中，获取大对象
		objects=json_object_array_get_idx (obj_arrs,i);
		
		//通过标签获得小包
		obj_ids=json_object_object_get (objects,"user_id");
		obj_names =json_object_object_get (objects,"user_name");
		
		//解析小包
		(*frs)[i].user_id = json_object_get_int(obj_ids);
		strcpy( (*frs)[i].user_name , json_object_get_string (obj_names) );
	}

	return len;
}
